<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    function observer(data) {
      if (!data || typeof data !== 'object') { return }
      Object.keys(data).forEach(key => {
        console.log(key);
        defineReactive(data, key, data[key])
      })
    }
    function defineReactive(obj, key, val) {
      const dep = new Dep()
      Object.defineProperty(obj, key, {
        enumerable: true,
        configurable: true,
        get() {
          // 每一个属性都是一个发布者
          dep.addSub(Dep.target)
          return val
        },
        set(newVal) {
          if (newVal === val) {
            return
          }
          dep.notify(newVal)
        }
      })
    }
    function cb() {
      console.log('视图更新啦');
    }

    class Dep {
      constructor() {
        this.subs = []
      }

      addSub(watcher) {
        this.subs.push(watcher)
      }

      notify(newVal) {
        this.subs.forEach(item => item.update(newVal))
      }
    }

    class Watcher {
      constructor() {
        Dep.target = this
      }

      update(newVal) {
        console.log('data update!', newVal);
      }
    }

    class Vue {
      constructor(options) {
        this.$data = options.data
        // 每一个组件只有一个观察者,会有多个发布者
        const watcher = new Watcher
        observer(this.$data, watcher)
        console.log('render', this.$data.name);
      }
    }
    let vm = new Vue({
      data: {
        name: 'ttq',
        msg: 'msg1',
        msg2: 'asdfasdf'
      }
    })
    setTimeout(() => {
      vm.$data.name = 'hhl'

    }, 3000)
  </script>
</body>

</html>